-- main.lua
-- 游戏主入口文件：负责游戏初始化和主循环 - 集成户外场景作为第一关
-- 修改：添加完整的战斗系统，包括Spine骨骼碰撞检测和敌人状态监视器

local Node = require("Node")
local Director = require("Director")
local Platformer = require("Platformer")
local Vec2 = require("Vec2")
local Rect = require("Rect")

-- 导入游戏模块
local KeyboardInput = require("keyboard_input")
local InputManager = require("input_manager")
local MovementSystem = require("movement_system")
local JumpSystem = require("jump_system")
local CombatSystem = require("combat_system")  -- 保留战斗系统
local ActionSystem = require("action_system")
local CharacterMonitor = require("Script.CharacterMonitor")
local CharacterManager = require("character_manager")
local MainMenu = require("main_menu")
local SceneManager = require("Script.SceneManager")

-- 导入关卡系统
local LevelManager = require("LevelManager")
local LevelTileConfig = require("LevelTileConfig")

-- 导入地形管理器
local LevelTerrainManager = require("LevelTerrainManager")

-- 导入户外场景管理器
local OutdoorSceneManager = require("OutdoorSceneManager")

-- 导入Boss场景管理器
local BossSceneManager = require("BossSceneManager")

local DisplayConfig = require("Script.DisplayConfig")

local MusicManager = require("Script.music_manager")

-- 导入战斗和血量系统
local HealthSystem = require("HealthSystem")

-- 导入敌人系统
local EnemySpawner = require("EnemySpawner")

-- 导入新的战斗核心系统和状态监视器
local CombatCoreSystem = require("CombatCoreSystem")
local EnemyStatusMonitor = require("EnemyStatusMonitor")

-- 游戏状态枚举
local GameState = {
    MAIN_MENU = "main_menu",  -- 主菜单状态
    PLAYING = "playing",      -- 游戏进行状态
    PAUSED = "paused",        -- 暂停状态
    TEST_SCENE = "test_scene" -- 测试场景状态
}

-- 游戏主类
local Game = {}
Game.__index = Game

-- 构造函数：创建新的游戏实例
function Game.new()
    local instance = {
        state = GameState.MAIN_MENU,  -- 初始状态为主菜单
        
        -- 系统组件
        sceneManager = nil,
        inputManager = nil,
        keyboardInput = nil,
        movementSystem = nil,
        jumpSystem = nil,
        combatSystem = nil,  -- 保留战斗系统
        actionSystem = nil,
        characterManager = nil,
        characterMonitor = nil,
        mainMenu = nil,
        levelManager = nil,
        terrainManager = nil,
        outdoorSceneManager = nil,
        
        -- Boss场景相关
        bossSceneManager = nil,
        bossTriggered = false,
        bossTriggerData = nil,
        
        -- 测试场景相关
        testScene = nil,
        testSceneNode = nil,
        enemySpawner = nil,
        
        -- 新的战斗系统组件
        combatCoreSystem = nil,       -- 战斗核心系统（Spine骨骼碰撞）
        enemyStatusMonitors = {},     -- 敌人状态监视器
        
        -- 其他系统组件
        healthSystem = nil,
        musicManager = nil,
        
        -- 游戏对象
        playerNode = nil,
        playerEntity = nil,
        playerCharacter = nil,
        scene = nil,
        cameraTarget = nil,
        
        -- Spine相关
        spineNode = nil,
        
        -- 场景类型
        currentSceneType = nil,    -- 当前场景类型: "outdoor" 或 "indoor" 或 "boss" 或 "test"
        
        -- 游戏配置
        gameConfig = {
            playerHealth = 200,
            musicVolume = 0.6,
            playerScale = 0.02,    -- 测试场景中为原来的十分之一
            enemyScale = 0.1       -- 敌人缩放
        },
        
        -- 键盘状态跟踪
        keyStates = {},
        justPressedKeys = {},
        
        -- 调试模式
        debugMode = true,
        
        -- 帧计时器
        frameCount = 0,
        gameTime = 0
    }
    return setmetatable(instance, Game)
end

-- 初始化游戏
function Game:initialize()
    -- 创建音乐管理器
    self.musicManager = MusicManager.new()
    self.musicManager:setVolume(self.gameConfig.musicVolume)

    -- 创建输入系统
    self.keyboardInput = KeyboardInput.new()
    self.inputManager = InputManager.new()
    self.inputManager:setKeyboardInput(self.keyboardInput)
    
    -- 创建场景管理器
    self.sceneManager = SceneManager.new()
    
    -- 注册场景
    self:registerScenes()
    
    -- 切换到主菜单
    self:switchToMainMenu()
    
    return true
end

-- 注册所有场景
function Game:registerScenes()
    -- 注册主菜单场景
    self.sceneManager:registerScene("MainMenu", function()
        return self:createMainMenuScene()
    end)
    
    -- 注册户外场景（作为第一关）
    self.sceneManager:registerScene("OutdoorScene", function(transitionData)
        return self:createOutdoorScene({id = "OutdoorScene"}, transitionData)
    end)
    
    -- 注册室内关卡场景（第二关）
    self.sceneManager:registerScene("LevelScene", function(transitionData)
        return self:createIndoorScene({id = "LevelScene"}, transitionData)
    end)
    
    -- 注册BOSS关卡场景
    self.sceneManager:registerScene("BossScene", function(transitionData)
        return self:createBossScene({id = "BossScene"}, transitionData)
    end)
    
    -- 注册测试场景（新增）
    self.sceneManager:registerScene("TestScene", function()
        return self:createTestScene()
    end)
end

-- 创建主菜单场景
function Game:createMainMenuScene()
    local scene = Node()
    
    -- 创建主菜单
    self.mainMenu = MainMenu.new(self.inputManager, self.sceneManager)
    self.mainMenu:setGameInstance(self)
    local menuNode = self.mainMenu:create()
    
    -- 添加到场景
    scene:addChild(menuNode)
    
    -- 注册键盘输入到场景
    if self.keyboardInput then
        self.keyboardInput:registerToScene(scene)
    end
    
    -- 播放主菜单音乐
    if self.musicManager then
        self.musicManager:playBGM("main_menu", true)
    end
    
    return scene
end

-- 创建户外场景（第一关）
function Game:createOutdoorScene(sceneConfig, transitionData)
    -- 使用 PlatformWorld 作为游戏场景
    local scene = Platformer.PlatformWorld()
    self.scene = scene
    
    -- 设置当前场景类型
    self.currentSceneType = "outdoor"
    
    -- 创建户外场景管理器
    self.outdoorSceneManager = OutdoorSceneManager.new()
    
    -- 创建运动系统 - 使用户外场景边界
    local sceneBounds = {
        left = 0,
        right = 24000,
        top = 8000,
        bottom = 0,
        width = 24000,
        height = 8000
    }
    
    self.movementSystem = MovementSystem.new(
        DisplayConfig.TARGET_WIDTH, 
        DisplayConfig.TARGET_HEIGHT, 
        sceneBounds,
        self.keyboardInput
    )
    
    -- 创建角色监视器
    self.characterMonitor = CharacterMonitor.new(self.movementSystem, "player")
    self.movementSystem:setCharacterMonitor(self.characterMonitor)
    
    -- 创建动作系统
    self.actionSystem = ActionSystem.new(self.characterMonitor, self.movementSystem)
    
    -- 创建战斗系统（使用J键攻击）
    self.combatSystem = CombatSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor, self.actionSystem)
    
    -- 设置动作系统的战斗系统引用
    self.actionSystem:setCombatSystem(self.combatSystem)
    
    -- 创建跳跃系统
    self.jumpSystem = JumpSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor)
    
    -- 创建角色管理器
    self.characterManager = CharacterManager.new()
    
    -- 创建血量系统
    self.healthSystem = HealthSystem.new()
    
    -- 设置角色管理器到血量系统
    self.healthSystem:setCharacterManager(self.characterManager)
    
    -- 设置血量系统到角色管理器
    self.characterManager:setHealthSystem(self.healthSystem)
    
    -- 获取户外场景的起始位置（在最左侧出生）
    local startPos = self.outdoorSceneManager:getPlayerStartPosition()
    
    -- 创建玩家角色
    local playerCreationSuccess, playerNode, playerEntity, playerCharacter = pcall(function()
        return self.characterManager:createCharacter("player", startPos, self.movementSystem, {
            maxSpeed = 800,
            mass = 1,
            radius = 25,
            health = self.gameConfig.playerHealth,
            maxHealth = self.gameConfig.playerHealth,
            healthBarOptions = {
                width = 200,
                height = 24,
                offsetY = 80
            }
        })
    end)
    
    if playerCreationSuccess and playerNode and playerEntity then
        self.playerNode = playerNode
        self.playerEntity = playerEntity
        self.playerCharacter = playerCharacter
    else
        return scene
    end
    
    -- 创建Spine动画节点
    local spineCreationSuccess, spineNode = pcall(function()
        return self.actionSystem:createSpineNode()
    end)
    
    if spineCreationSuccess and spineNode then
        self.spineNode = spineNode
        
        if self.playerNode then
            self.playerNode:addChild(self.spineNode)
            
            local setupSuccess = self.actionSystem:setSpineNode(self.spineNode)
        end
    end
    
    -- 将角色添加到场景
    self.characterManager:addAllCharactersToScene(scene)
    
    -- 初始化户外场景管理器
    local outdoorInitSuccess = self.outdoorSceneManager:initialize(scene, self.playerNode, self.sceneManager)
    if not outdoorInitSuccess then
        return scene
    end
    
    -- 设置地面平台到运动系统
    local groundPlatforms = self.outdoorSceneManager:getGroundPlatforms()
    if groundPlatforms then
        self.movementSystem:clearGroundPlatforms()
        for _, platform in ipairs(groundPlatforms) do
            self.movementSystem:addGroundPlatform(platform)
        end
    end
    
    -- 设置相机跟随目标
    if self.playerNode then
        self.cameraTarget = Node()
        self.cameraTarget.position = Vec2(0, 200)
        
        self.playerNode:addChild(self.cameraTarget)
        
        self.sceneManager:setCameraTarget(scene, self.cameraTarget)
    end
    
    -- 注册键盘输入到场景
    if self.keyboardInput then
        self.keyboardInput:registerToScene(scene)
    end
    
    -- 设置游戏状态
    self.state = GameState.PLAYING
    
    -- 播放游戏音乐
    if self.musicManager then
        self.musicManager:playBGM("gameplay", true)
    end
    
    return scene
end

-- 创建室内场景（第二关）
function Game:createIndoorScene(sceneConfig, transitionData)
    -- 使用 PlatformWorld 作为游戏场景
    local scene = Platformer.PlatformWorld()
    self.scene = scene

    -- 设置当前场景类型
    self.currentSceneType = "indoor"
    
    -- 创建地形管理器
    self.terrainManager = LevelTerrainManager.new()
    
    -- 初始化地形数据
    self.terrainManager:initialize()
    
    -- 创建运动系统 - 使用关卡边界
    local levelBounds = LevelTileConfig.getLevelBounds()
    
    self.movementSystem = MovementSystem.new(
        DisplayConfig.TARGET_WIDTH, 
        DisplayConfig.TARGET_HEIGHT, 
        levelBounds,
        self.keyboardInput
    )
    
    -- 设置地形管理器到运动系统
    self.movementSystem:setTerrainManager(self.terrainManager)
    
    -- 设置Boss触发器回调
    self.movementSystem:setBossTriggerCallback(function(triggerData)
        self:handleBossTrigger(triggerData)
    end)
    
    -- 创建关卡管理器
    self.levelManager = LevelManager.new()
    
    -- 初始化关卡管理器
    local levelInitSuccess = self.levelManager:initialize(scene, self.movementSystem)
    if not levelInitSuccess then
        return scene
    end
    
    -- 设置运动系统的关卡管理器引用
    self.movementSystem:setLevelManager(self.levelManager)
    
    -- 创建角色监视器
    self.characterMonitor = CharacterMonitor.new(self.movementSystem, "player")
    self.movementSystem:setCharacterMonitor(self.characterMonitor)
    
    -- 创建动作系统
    self.actionSystem = ActionSystem.new(self.characterMonitor, self.movementSystem)
    
    -- 创建战斗系统（使用J键攻击）
    self.combatSystem = CombatSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor, self.actionSystem)
    
    -- 设置动作系统的战斗系统引用
    self.actionSystem:setCombatSystem(self.combatSystem)
    
    -- 创建跳跃系统
    self.jumpSystem = JumpSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor)
    
    -- 创建角色管理器
    self.characterManager = CharacterManager.new()
    
    -- 创建血量系统
    self.healthSystem = HealthSystem.new()
    
    -- 设置角色管理器到血量系统
    self.healthSystem:setCharacterManager(self.characterManager)
    
    -- 设置血量系统到角色管理器
    self.characterManager:setHealthSystem(self.healthSystem)
    
    -- 使用关卡管理器提供的起始位置
    local startPos = self.levelManager:getPlayerStartPosition()
    
    -- 如果是从户外场景切换过来，调整起始位置为左侧入口
    if transitionData and transitionData.fromDirection == "left" then
        startPos.x = 100
    -- 如果是从Boss场景返回，使用返回位置
    elseif transitionData and transitionData.fromDirection == "right" and transitionData.returnPosition then
        startPos = transitionData.returnPosition
    end
    
    local playerStartPos = {x = startPos.x, y = startPos.y}
    
    -- 创建玩家角色
    local playerCreationSuccess, playerNode, playerEntity, playerCharacter = pcall(function()
        return self.characterManager:createCharacter("player", playerStartPos, self.movementSystem, {
            maxSpeed = 800,
            mass = 1,
            radius = 25,
            health = transitionData and transitionData.playerHealth or self.gameConfig.playerHealth,
            maxHealth = transitionData and transitionData.playerMaxHealth or self.gameConfig.playerHealth,
            healthBarOptions = {
                width = 200,
                height = 24,
                offsetY = 80
            }
        })
    end)
    
    if playerCreationSuccess and playerNode and playerEntity then
        self.playerNode = playerNode
        self.playerEntity = playerEntity
        self.playerCharacter = playerCharacter
    else
        return scene
    end

    -- 创建Spine动画节点
    local spineCreationSuccess, spineNode = pcall(function()
        return self.actionSystem:createSpineNode()
    end)
    
    if spineCreationSuccess and spineNode then
        self.spineNode = spineNode
        
        if self.playerNode then
            self.playerNode:addChild(self.spineNode)
            
            local setupSuccess = self.actionSystem:setSpineNode(self.spineNode)
        end
    end

    -- 将角色添加到场景
    self.characterManager:addAllCharactersToScene(scene)
    
    -- 设置相机跟随目标
    if self.playerNode then
        self.cameraTarget = Node()
        self.cameraTarget.position = Vec2(0, 200)
        
        self.playerNode:addChild(self.cameraTarget)
        
        self.sceneManager:setCameraTarget(scene, self.cameraTarget)
    end
    
    -- 注册键盘输入到场景
    if self.keyboardInput then
        self.keyboardInput:registerToScene(scene)
    end
    
    -- 设置游戏状态
    self.state = GameState.PLAYING
    
    -- 播放游戏音乐
    if self.musicManager then
        self.musicManager:playBGM("gameplay", true)
    end
    
		-- 创建战斗伤害检测系统
    self.combatDamageSystem = require("CombatDamageSystem").new()
    
    -- 创建敌人生成器
    self.enemySpawner = EnemySpawner.new(scene, self.playerEntity, levelBounds)
    
    -- 在关卡内随机生成敌人
    if self.levelManager then
        self.enemySpawner:spawnEnemiesInLevel(self.levelManager, 1)
    end


    return scene
end

-- 创建Boss场景
function Game:createBossScene(sceneConfig, transitionData)
    -- 使用 PlatformWorld 作为游戏场景
    local scene = Platformer.PlatformWorld()
    self.scene = scene

    -- 设置当前场景类型
    self.currentSceneType = "boss"
    
    -- 创建Boss场景管理器
    self.bossSceneManager = BossSceneManager.new()
    
    -- 获取触发器位置（从过渡数据中）
    local triggerPosition = transitionData and transitionData.triggerPosition or {x = 0, y = 0}
    
    -- 创建运动系统 - 使用Boss房边界
    local sceneBounds = {
        left = 0,
        right = 2844,
        top = 1600,
        bottom = 0,
        width = 2844,
        height = 1600
    }


    
    self.movementSystem = MovementSystem.new(
        DisplayConfig.TARGET_WIDTH, 
        DisplayConfig.TARGET_HEIGHT, 
        sceneBounds,
        self.keyboardInput
    )
    
    -- 创建角色监视器
    self.characterMonitor = CharacterMonitor.new(self.movementSystem, "player")
    self.movementSystem:setCharacterMonitor(self.characterMonitor)
    
    -- 创建动作系统
    self.actionSystem = ActionSystem.new(self.characterMonitor, self.movementSystem)
    
    -- 创建战斗系统（使用J键攻击）
    self.combatSystem = CombatSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor, self.actionSystem)
    
    -- 设置动作系统的战斗系统引用
    self.actionSystem:setCombatSystem(self.combatSystem)
    
    -- 创建跳跃系统
    self.jumpSystem = JumpSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor)
    
    -- 创建角色管理器
    self.characterManager = CharacterManager.new()
    
    -- 创建血量系统
    self.healthSystem = HealthSystem.new()
    
    -- 设置角色管理器到血量系统
    self.healthSystem:setCharacterManager(self.characterManager)
    
    -- 设置血量系统到角色管理器
    self.characterManager:setHealthSystem(self.healthSystem)
    
    -- 初始化Boss场景管理器
    local bossInitSuccess = self.bossSceneManager:initialize(
        scene, 
        nil, -- playerNode将在后面设置
        self.sceneManager,
        triggerPosition
    )
    
    if not bossInitSuccess then
        return scene
    end
    
    -- 获取Boss场景的起始位置
    local startPos = self.bossSceneManager:getPlayerStartPosition()
    
    -- 创建玩家角色
    local playerCreationSuccess, playerNode, playerEntity, playerCharacter = pcall(function()
        return self.characterManager:createCharacter("player", startPos, self.movementSystem, {
            maxSpeed = 800,
            mass = 1,
            radius = 25,
            health = transitionData and transitionData.playerHealth or self.gameConfig.playerHealth,
            maxHealth = transitionData and transitionData.playerMaxHealth or self.gameConfig.playerHealth,
            healthBarOptions = {
                width = 200,
                height = 24,
                offsetY = 80
            }
        })
    end)
    
    if playerCreationSuccess and playerNode and playerEntity then
        self.playerNode = playerNode
        self.playerEntity = playerEntity
        self.playerCharacter = playerCharacter
        
        -- 更新Boss场景管理器的玩家节点引用
        self.bossSceneManager.playerNode = self.playerNode
    else
        return scene
    end
    
    -- 设置地面平台到运动系统
    local groundPlatforms = self.bossSceneManager:getGroundPlatforms()
    if groundPlatforms then
        self.movementSystem:clearGroundPlatforms()
        for _, platform in ipairs(groundPlatforms) do
            self.movementSystem:addGroundPlatform(platform)
        end
    end
    
    -- 创建Spine动画节点
    local spineCreationSuccess, spineNode = pcall(function()
        return self.actionSystem:createSpineNode()
    end)
    
    if spineCreationSuccess and spineNode then
        self.spineNode = spineNode
        
        if self.playerNode then
            self.playerNode:addChild(self.spineNode)
            
            local setupSuccess = self.actionSystem:setSpineNode(self.spineNode)
        end
    end
    
    -- 将角色添加到场景
    self.characterManager:addAllCharactersToScene(scene)
    
    -- 设置相机跟随目标
    if self.playerNode then
        self.cameraTarget = Node()
        self.cameraTarget.position = Vec2(0, 200)
        
        self.playerNode:addChild(self.cameraTarget)
        
        self.sceneManager:setCameraTarget(scene, self.cameraTarget)
    end
    
    -- 注册键盘输入到场景
    if self.keyboardInput then
        self.keyboardInput:registerToScene(scene)
    end

		 -- 生成Boss
    if self.bossSceneManager then
        self.bossSceneManager:spawnBoss()
    end
    
    -- 设置游戏状态
    self.state = GameState.PLAYING
    
    -- 播放Boss战斗音乐
    if self.musicManager then
        self.musicManager:playBGM("boss", true)
    end
    
    return scene
end

-- 添加更新方法以检查位置是否低于-500：
function Game:checkEntityPositions()
    -- 检查玩家位置
    if self.playerEntity and self.playerEntity.position.y < -500 then
        print("玩家掉出世界，死亡")
        self:handlePlayerDeath()
        return
    end
    
    -- 检查测试场景中的敌人位置
    if self.enemySpawner then
        local enemies = self.enemySpawner:getEnemies()
        for enemyId, enemy in pairs(enemies) do
            if enemy.data and enemy.data.position and enemy.data.position.y < -500 then
                print(string.format("敌人 %s 掉出世界，死亡", enemyId))
                self.enemySpawner:destroyEnemy(enemyId)
            end
        end
    end
    
    -- 检查Boss位置
    if self.bossSceneManager and self.bossSceneManager.bossEntity then
        local boss = self.bossSceneManager.bossEntity
        if boss.position and boss.position.y < -500 then
            print("Boss掉出世界，死亡")
            self.bossSceneManager:onBossDefeated()
        end
    end
end



-- 创建测试场景（新增完整战斗系统）
function Game:createTestScene()
    -- 创建测试场景节点
    self.testSceneNode = Node()
    self.scene = self.testSceneNode
    
    -- 设置当前场景类型
    self.currentSceneType = "test"
    
    -- 创建测试场景数据结构
    self.testScene = {
        scene = self.testSceneNode,
        movementSystem = nil,
        playerEntity = nil,
        playerNode = nil,
        enemySpawner = nil,
        characterMonitor = nil,
        actionSystem = nil,
        combatSystem = nil,
        jumpSystem = nil,
        combatCoreSystem = nil,
        
        -- 测试场景配置
        sceneBounds = {
            left = 0,
            right = 2560,
            top = 1600,
            bottom = 0,
            width = 2560,
            height = 1600
        },
        
        -- 背景图片
        background = nil,
        
        -- 敌人生成位置
        spawnPositions = {
            {x = 500, y = 300},
            {x = 1000, y = 300},
            {x = 1500, y = 300},
            {x = 2000, y = 300}
        },
        currentSpawnIndex = 1,
        
        debugMode = true
    }
    
    -- 设置背景（使用图片1.png）
    local Sprite = require("Sprite")
    local bg = Sprite("Image/1.png")
    if bg then
        bg.x = self.testScene.sceneBounds.width / 2
        bg.y = self.testScene.sceneBounds.height / 2
        self.testScene.background = bg
        self.testSceneNode:addChild(bg)
    end
    
    -- 创建运动系统（玩家专用）
    self.movementSystem = MovementSystem.new(
        self.testScene.sceneBounds.width,
        self.testScene.sceneBounds.height,
        self.testScene.sceneBounds,
        self.keyboardInput
    )
    self.testScene.movementSystem = self.movementSystem
    
    -- 添加地面平台
    local groundPlatform = {
        x = 0,
        y = 200,
        width = self.testScene.sceneBounds.width,
        height = 50
    }
    self.movementSystem:addGroundPlatform(groundPlatform)
    
    -- 创建玩家（在最左端生成）
    local startPos = {x = 100, y = 300}
    
    -- 创建玩家实体
    local playerEntityData = {
        id = "player",
        position = {x = startPos.x, y = startPos.y},
        velocity = {x = 0, y = 0},
        maxSpeed = 400,
        mass = 1,
        radius = 12.5,  -- 原来的十分之一
        health = self.gameConfig.playerHealth,
        maxHealth = self.gameConfig.playerHealth,
        isAlive = true,
        moveInput = 0,
        facingDirection = 1,
        isGrounded = true
    }
    
    local success = self.movementSystem:registerEntity(playerEntityData)
    if not success then
        print("错误：注册玩家到运动系统失败")
        return self.testSceneNode
    end
    
    self.playerEntity = self.movementSystem:getEntity("player")
    self.testScene.playerEntity = self.playerEntity
    
    -- 创建玩家节点
    self.playerNode = Node()
    self.playerNode.x = startPos.x
    self.playerNode.y = startPos.y
    self.testScene.playerNode = self.playerNode
    self.testSceneNode:addChild(self.playerNode)
    
    -- 创建角色监视器（为攻击系统使用）
    self.characterMonitor = CharacterMonitor.new(self.movementSystem, "player")
    self.movementSystem:setCharacterMonitor(self.characterMonitor)
    self.testScene.characterMonitor = self.characterMonitor
    
    -- 创建动作系统
    self.actionSystem = ActionSystem.new(self.characterMonitor, self.movementSystem)
    self.testScene.actionSystem = self.actionSystem
    
    -- 创建战斗系统（使用J键攻击）
    self.combatSystem = CombatSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor, self.actionSystem)
    self.testScene.combatSystem = self.combatSystem
    
    -- 设置动作系统的战斗系统引用
    self.actionSystem:setCombatSystem(self.combatSystem)
    
    -- 创建跳跃系统
    self.jumpSystem = JumpSystem.new(self.movementSystem, self.keyboardInput, self.characterMonitor)
    self.testScene.jumpSystem = self.jumpSystem
    
    -- 创建玩家Spine（缩小到十分之一）
    local Spine = require("Spine")
    local playerSpine = Spine("model/que/que")
    if playerSpine then
        playerSpine.scaleX = self.gameConfig.playerScale  -- 原来的十分之一
        playerSpine.scaleY = self.gameConfig.playerScale
        
        -- 设置Spine节点到动作系统
        self.actionSystem:setSpineNode(playerSpine)
        self.playerNode:addChild(playerSpine)
        self.spineNode = playerSpine
    end
    
    -- 创建战斗核心系统
    self.combatCoreSystem = CombatCoreSystem.new()
    self.testScene.combatCoreSystem = self.combatCoreSystem
    
    -- 创建敌人生成器（使用独立的敌人移动系统）
    self.enemySpawner = EnemySpawner.new(
        self.testSceneNode, 
        self.playerEntity, 
        self.testScene.sceneBounds
    )
    self.testScene.enemySpawner = self.enemySpawner
    
    -- 设置地面平台到敌人生成器
    self.enemySpawner:setGroundPlatforms({groundPlatform})
    
    -- 初始化敌人状态监视器
    self.enemyStatusMonitors = {}
    self.testScene.enemyStatusMonitors = self.enemyStatusMonitors
    
    -- 注册键盘输入到场景
    if self.keyboardInput then
        self.keyboardInput:registerToScene(self.testSceneNode)
    end
    
    -- 设置游戏状态
    self.state = GameState.TEST_SCENE
    
    -- 播放游戏音乐（或静音）
    if self.musicManager then
        self.musicManager:stopBGM()
    end
    
    print("====================================")
    print("测试场景创建完成")
    print("玩家生成在最左端 (100, 300)")
    print("控制方式：")
    print("  A/D: 左右移动")
    print("  Space: 跳跃")
    print("  J: 攻击")
    print("  Q: 切换武器模式")
    print("  Shift: 翻滚")
    print("  F2: 生成剑士敌人")
    print("  F3: 生成弓箭手敌人")
    print("  F4: 生成刀兵敌人")
    print("  F1: 重新进入测试场景")
    print("  ESC: 返回主菜单")
    print("====================================")
    
    return self.testSceneNode
end

-- 处理Boss触发器
function Game:handleBossTrigger(triggerData)
    if self.bossTriggered then return end
    
    print("====================================")
    print("处理Boss触发器")
    print(string.format("触发器位置: (%.1f, %.1f)", triggerData.x, triggerData.y))
    print("====================================")
    
    self.bossTriggered = true
    self.bossTriggerData = triggerData
    
    -- 切换到Boss场景
    self:switchToBossScene(triggerData)
end

-- 切换到Boss场景
function Game:switchToBossScene(triggerData)
    if not self.sceneManager then return end
    
    -- 保存玩家当前状态
    local playerHealth = self.playerCharacter and self.playerCharacter.health or self.gameConfig.playerHealth
    local playerMaxHealth = self.playerCharacter and self.playerCharacter.maxHealth or self.gameConfig.playerHealth
    
    -- 清理当前游戏系统（但保留玩家状态）
    self:cleanupGameSystems()
    
    -- 切换到Boss场景
    local success = self.sceneManager:switchToScene("BossScene", {
        triggerPosition = {x = triggerData.x, y = triggerData.y},
        transitionType = "main_to_boss",
        playerHealth = playerHealth,
        playerMaxHealth = playerMaxHealth
    })
    
    if success then
        print("成功切换到Boss关卡")
    else
        print("切换到Boss关卡失败")
        self.bossTriggered = false
        self.bossTriggerData = nil
    end
end

-- 切换到测试场景
function Game:switchToTestScene()
    -- 设置游戏状态
    self.state = GameState.TEST_SCENE
    
    -- 停止当前音乐
    if self.musicManager then
        self.musicManager:stopBGM()
    end
    
    -- 清理当前游戏系统
    self:cleanupGameSystems()
    
    -- 切换到测试场景
    local success = self.sceneManager:switchToScene("TestScene")
    if success then
        if self.inputManager then
            self.inputManager:pushContext("Game")
        end
    end
    
    return success
end

-- 清理游戏系统
function Game:cleanupGameSystems()
    -- 清理户外场景管理器
    if self.outdoorSceneManager then
        self.outdoorSceneManager:cleanup()
        self.outdoorSceneManager = nil
    end
    
    -- 清理Boss场景管理器
    if self.bossSceneManager then
        self.bossSceneManager:cleanup()
        self.bossSceneManager = nil
    end
    
    -- 清理地形管理器
    if self.terrainManager then
        self.terrainManager:cleanup()
        self.terrainManager = nil
    end
    
    -- 清理关卡管理器
    if self.levelManager then
        self.levelManager:cleanup()
        self.levelManager = nil
    end
    
    -- 清理角色管理器
    if self.characterManager then
        self.characterManager:reset()
        self.characterManager = nil
    end
    
    -- 清理动作系统
    if self.actionSystem then
        self.actionSystem:cleanup()
        self.actionSystem = nil
    end
    
    -- 清理战斗系统（保留）
    if self.combatSystem then
        self.combatSystem:cleanup()
        self.combatSystem = nil
    end
    
    -- 清理战斗核心系统
    if self.combatCoreSystem then
        self.combatCoreSystem:reset()
        self.combatCoreSystem = nil
    end
    
    -- 清理跳跃系统
    if self.jumpSystem then
        self.jumpSystem:reset()
        self.jumpSystem = nil
    end
    
    -- 清理运动系统
    if self.movementSystem then
        self.movementSystem:reset()
        self.movementSystem = nil
    end
    
    -- 清理角色监视器
    if self.characterMonitor then
        self.characterMonitor:reset()
        self.characterMonitor = nil
    end
    
    -- 清理Spine节点
    if self.spineNode then
        if self.spineNode.parent then
            self.spineNode:removeFromParent()
        end
        self.spineNode = nil
    end
    
    -- 清理相机目标
    if self.cameraTarget then
        if self.cameraTarget.parent then
            self.cameraTarget:removeFromParent()
        end
        self.cameraTarget = nil
    end
    
    -- 清理测试场景
    if self.testScene then
        -- 清理敌人状态监视器
        for enemyId, statusData in pairs(self.enemyStatusMonitors) do
            if statusData and statusData.monitor then
                statusData.monitor:cleanup()
            end
        end
        self.enemyStatusMonitors = {}
        
        if self.enemySpawner then
            self.enemySpawner:cleanup()
            self.enemySpawner = nil
        end
        
        if self.testSceneNode and self.testSceneNode.parent then
            self.testSceneNode:removeFromParent()
        end
        
        self.testScene = nil
        self.testSceneNode = nil
    end
    
    -- 清理角色节点引用
    self.playerNode = nil
    self.playerEntity = nil
    self.playerCharacter = nil
    
    -- 停止当前音乐
    if self.musicManager then
        self.musicManager:stopBGM()
    end
    
    -- 重置Boss触发状态
    self.bossTriggered = false
    self.bossTriggerData = nil
    
    -- 重置场景类型
    self.currentSceneType = nil
    
    -- 重置帧计时器
    self.frameCount = 0
    self.gameTime = 0
end

-- 开始游戏（从户外场景开始）
function Game:startGame()
    -- 设置游戏状态
    self.state = GameState.PLAYING

    -- 停止主菜单音乐
    if self.musicManager then
        self.musicManager:stopBGM()
    end
    
    -- 清理当前场景
    self:cleanupGameSystems()

    -- 切换到户外场景
    local success = self.sceneManager:switchToScene("OutdoorScene")
    if success then
        if self.inputManager then
            self.inputManager:pushContext("Game")
        end
    end
    
    return success
end

-- 切换到主菜单
function Game:switchToMainMenu()
    -- 设置游戏状态
    self.state = GameState.MAIN_MENU
    
    -- 清理游戏系统
    self:cleanupGameSystems()

    -- 播放主菜单音乐
    if self.musicManager then
        self.musicManager:playBGM("main_menu", true)
    end
    
    -- 切换到主菜单场景
    local success = self.sceneManager:switchToScene("MainMenu")
    if success then
        if self.inputManager then
            self.inputManager:pushContext("UI")
        end
    end
    
    return success
end

-- 更新键盘状态
function Game:updateKeyStates()
    -- 清空刚刚按下的键
    self.justPressedKeys = {}
    
    -- 更新键盘输入
    if self.keyboardInput then
        -- 检查重要按键
        local keysToCheck = {"F1", "F2", "F3", "F4", "Escape", "A", "D", "Space", "J", "Q", "Shift", "LShift", "RShift"}
        
        for _, key in ipairs(keysToCheck) do
            local wasPressed = self.keyStates[key] or false
            local isPressed = self.keyboardInput:isKeyPressed(key)
            
            -- 记录按键状态
            self.keyStates[key] = isPressed
            
            -- 检测刚刚按下的键
            if isPressed and not wasPressed then
                self.justPressedKeys[key] = true
            end
        end
    end
end

-- 处理键盘输入
function Game:handleKeyboardInput()
    -- 处理全局热键（在任何状态下都有效）
    if self.justPressedKeys["F1"] then
        print("F1键按下，进入测试场景")
        self:switchToTestScene()
        return
    end
    
    -- 根据游戏状态处理不同的输入
    if self.state == GameState.TEST_SCENE then
        self:handleTestSceneInput()
    elseif self.state == GameState.PLAYING then
        self:handlePlayingInput()
    elseif self.state == GameState.MAIN_MENU then
        self:handleMainMenuInput()
    end
end

-- 处理测试场景输入
function Game:handleTestSceneInput()
    -- ESC键返回主菜单
    if self.justPressedKeys["Escape"] then
        print("ESC键按下，返回主菜单")
        self:switchToMainMenu()
        return
    end
    
    -- 生成敌人
    if self.justPressedKeys["F2"] then
        print("F2键按下，生成剑士")
        self:spawnTestEnemy("sword")
    end
    
    if self.justPressedKeys["F3"] then
        print("F3键按下，生成弓箭手")
        self:spawnTestEnemy("archer")
    end
    
    if self.justPressedKeys["F4"] then
        print("F4键按下，生成刀兵")
        self:spawnTestEnemy("broadsword")
    end
    
    -- 注意：玩家的移动和攻击输入由各自的系统处理
    -- MovementSystem、CombatSystem等会通过keyboardInput直接读取按键状态
end

-- 处理游戏进行中的输入
function Game:handlePlayingInput()
    -- ESC键返回主菜单
    if self.justPressedKeys["Escape"] then
        print("ESC键按下，返回主菜单")
        self:switchToMainMenu()
        return
    end
end

-- 处理主菜单输入
function Game:handleMainMenuInput()
    -- 主菜单输入主要由MainMenu模块处理
    -- 这里只处理全局热键
end

-- 在测试场景中生成敌人（带状态监视器）
function Game:spawnTestEnemy(enemyType)
    if not self.testScene or not self.enemySpawner then
        print("错误：测试场景未初始化")
        return
    end
    
    -- 获取下一个生成位置
    local spawnPos = self.testScene.spawnPositions[self.testScene.currentSpawnIndex]
    if not spawnPos then
        self.testScene.currentSpawnIndex = 1
        spawnPos = self.testScene.spawnPositions[1]
    end
    
    -- 生成敌人
    local enemy = self.enemySpawner:spawnEnemy(enemyType, spawnPos)
    
    if enemy then
        print(string.format("生成%s敌人，位置: (%d, %d)", enemyType, spawnPos.x, spawnPos.y))
        
        -- 为敌人创建状态监视器和血条
        local statusMonitor = EnemyStatusMonitor.new(enemy.id, enemyType)
        
        -- 创建血条
        local healthBarNode = statusMonitor:createHealthBar()
        if healthBarNode then
            -- 设置血条初始位置
            statusMonitor:setHealthBarPosition(spawnPos.x, spawnPos.y)
            self.testSceneNode:addChild(healthBarNode)
        end
        
        -- 存储状态监视器
        self.enemyStatusMonitors[enemy.id] = {
            monitor = statusMonitor,
            enemyRef = enemy
        }
        
        -- 更新生成位置索引
        self.testScene.currentSpawnIndex = self.testScene.currentSpawnIndex + 1
        if self.testScene.currentSpawnIndex > #self.testScene.spawnPositions then
            self.testScene.currentSpawnIndex = 1
        end
        
        -- 为玩家攻击注册命中框
        self:registerPlayerAttackHitBox()
    end
end

-- 注册玩家攻击命中框
function Game:registerPlayerAttackHitBox()
    if not self.combatCoreSystem or not self.spineNode then return end
    
    -- 根据当前武器模式设置不同的攻击伤害
    local currentMode = "chi"  -- 默认模式
    if self.characterMonitor then
        currentMode = self.characterMonitor.currentMode or "chi"
    end
    
    local damageByMode = {
        chi = 30,
        chui = 40,
        zao = 50
    }
    
    local damage = damageByMode[currentMode] or 30
    
    -- 注册攻击命中框（基于武器骨骼）
    local hitBoxName = "attack_" .. currentMode
    
    -- 根据武器模式选择不同的骨骼
    local bonePositions = {}
    if currentMode == "chi" then
        bonePositions = {
            weapon = {x = 0, y = 0}  -- 武器骨骼位置
        }
    elseif currentMode == "chui" then
        bonePositions = {
            weapon = {x = 0, y = 0},
            hammer = {x = 0, y = 0}  -- 锤子骨骼
        }
    elseif currentMode == "zao" then
        bonePositions = {
            weapon = {x = 0, y = 0},
            drill = {x = 0, y = 0}   -- 凿子骨骼
        }
    end
    
    self.combatCoreSystem:registerHitBox("player", hitBoxName, bonePositions, damage, 0.3)
    
    if self.debugMode then
        print(string.format("注册玩家攻击命中框: 模式=%s, 伤害=%d", currentMode, damage))
    end
end

-- 更新游戏
function Game:update(dt)
    -- 更新帧计时器
    self.frameCount = self.frameCount + 1
    self.gameTime = self.gameTime + dt
    
    -- 更新键盘状态
    self:updateKeyStates()
    
    -- 处理键盘输入
    self:handleKeyboardInput()
    
    -- 更新输入系统
    if self.inputManager then
        self.inputManager:update(dt)
    end
    
    -- 更新键盘输入系统
    if self.keyboardInput then
        self.keyboardInput:update(dt)
    end
    
    -- 根据游戏状态执行不同的更新逻辑
    if self.state == GameState.PLAYING then
        self:updatePlayingState(dt)
    elseif self.state == GameState.TEST_SCENE then
        self:updateTestSceneState(dt)
    elseif self.state == GameState.MAIN_MENU then
        self:updateMainMenuState(dt)
    elseif self.state == GameState.PAUSED then
        self:updatePausedState(dt)
    end
end

-- 更新游戏进行状态
function Game:updatePlayingState(dt)
    -- 更新跳跃系统
    if self.jumpSystem then
        self.jumpSystem:update(dt)
    end
    
    -- 更新战斗系统（J键攻击系统）
    if self.combatSystem then
        self.combatSystem:update(dt)
    end
    
    -- 更新运动系统
    if self.movementSystem then
        self.movementSystem:update(dt)
    end
    
    -- 根据场景类型更新对应的管理器
    if self.currentSceneType == "outdoor" then
        -- 更新户外场景管理器
        if self.outdoorSceneManager and self.playerNode then
            self.outdoorSceneManager:update(dt, self.playerNode.x, self.playerNode.y)
        end
    elseif self.currentSceneType == "indoor" then
        -- 更新地形管理器
        if self.terrainManager and self.playerNode then
            self.terrainManager:updateActiveTerrain(self.playerNode.x, self.playerNode.y)
        end
        
        -- 更新关卡管理器
        if self.levelManager and self.playerNode then
            self.levelManager:update(dt, self.playerNode.x, self.playerNode.y)
        end
    elseif self.currentSceneType == "boss" then
        -- 更新Boss场景管理器
        if self.bossSceneManager and self.playerNode then
            self.bossSceneManager:update(dt, self.playerNode.x, self.playerNode.y)
        end
    end
    
    -- 更新角色状态监视器
    if self.characterMonitor then
        self.characterMonitor:update(dt)
    end
    
    -- 更新动画系统（包括攻击动画）
    if self.actionSystem then
        self.actionSystem:update(dt)
    end
    
    -- 更新角色管理器
    if self.characterManager then
        self.characterManager:update(dt)
    end

		 -- 更新战斗伤害检测系统
    if self.combatDamageSystem then
        self.combatDamageSystem:update(dt)
        
        -- 检查玩家攻击
        if self.playerEntity and self.actionSystem and self.actionSystem.isAttackAnimation then
            -- 获取玩家信息
            local playerPos = self.playerEntity.position
            local facingRight = self.playerEntity.facingDirection == 1
            local currentMode = self.characterMonitor:getCurrentMode()
            
            -- 注册玩家攻击
            self.combatDamageSystem:registerPlayerAttack(
                "player",
                playerPos,
                facingRight,
                currentMode,
                self.combatSystem.currentCombo or 1
            )
        end
        
        -- 检查敌人是否被玩家攻击
        if self.enemySpawner then
            local enemies = self.enemySpawner:getEnemies()
            for enemyId, enemy in pairs(enemies) do
                if enemy.data and enemy.data.isAlive then
                    local underAttack, damage = self.combatDamageSystem:checkEnemyUnderAttack(
                        enemyId,
                        enemy.data.position.x,
                        enemy.data.position.y,
                        enemy.data.radius or 20
                    )
                    
                    if underAttack then
                        self.enemySpawner:applyDamageToEnemy(enemyId, damage)
                    end
                end
            end
        end
        
        -- 检查玩家是否被敌人攻击
        if self.playerEntity then
            local underAttack, damage = self.combatDamageSystem:checkPlayerUnderAttack(
                self.playerEntity.position.x,
                self.playerEntity.position.y,
                self.playerEntity.radius or 25
            )
            
            if underAttack then
                -- 对玩家应用伤害
                if self.characterManager then
                    self.characterManager:updateCharacterHealth("player", -damage)
                end
            end
        end
    end
    
    -- 检查实体位置
    self:checkEntityPositions()

    
    -- 检查玩家死亡
    if self.playerCharacter and self.playerCharacter.health and self.playerCharacter.health <= 0 then
        self:handlePlayerDeath()
    end
end

-- 更新测试场景状态
function Game:updateTestSceneState(dt)
    -- 更新跳跃系统
    if self.jumpSystem then
        self.jumpSystem:update(dt)
    end
    
    -- 更新战斗系统（J键攻击系统）
    if self.combatSystem then
        self.combatSystem:update(dt)
    end
    
    -- 更新运动系统
    if self.movementSystem then
        self.movementSystem:update(dt)
    end
    
    -- 更新角色状态监视器
    if self.characterMonitor then
        self.characterMonitor:update(dt)
    end
    
    -- 更新动画系统（包括攻击动画）
    if self.actionSystem then
        self.actionSystem:update(dt)
    end
    
    -- 更新战斗核心系统
    if self.combatCoreSystem then
        self.combatCoreSystem:update(dt)
        
        -- 更新玩家攻击命中框位置
        if self.spineNode then
            self.combatCoreSystem:updateHitBoxPositions("player", self.spineNode)
        end
    end
    
    -- 更新玩家节点位置
    if self.playerEntity then
        local entity = self.movementSystem:getEntity("player")
        if entity then
            if self.playerNode then
                self.playerNode.x = entity.position.x
                self.playerNode.y = entity.position.y
            end
            
            -- 更新玩家实体数据
            self.playerEntity.position.x = entity.position.x
            self.playerEntity.position.y = entity.position.y
            self.playerEntity.velocity.x = entity.velocity.x
            self.playerEntity.velocity.y = entity.velocity.y
            self.playerEntity.isGrounded = entity.isGrounded
            self.playerEntity.facingDirection = entity.lastDirection
        end
    end
    
    -- 更新敌人（使用独立的敌人移动系统）
    if self.enemySpawner then
        self.enemySpawner:update(dt)
    end
    
    -- 更新敌人状态监视器
    self:updateEnemyStatusMonitors(dt)
    
    -- 检测战斗碰撞
    self:checkCombatCollisions()
    
    -- 边界检查
    if self.playerEntity then
        self:checkTestSceneBoundaries()
    end
    
    -- 检查玩家死亡
    if self.playerEntity and self.playerEntity.health and self.playerEntity.health <= 0 then
        self:handlePlayerDeath()
    end
    
    -- 调试信息（每秒输出一次）
    if self.debugMode and self.frameCount % 60 == 0 then
        local enemyCount = self.enemySpawner and self.enemySpawner:getEnemyCount() or 0
        local monitorCount = 0
        for _ in pairs(self.enemyStatusMonitors) do
            monitorCount = monitorCount + 1
        end
        print(string.format("测试场景状态: 敌人=%d, 状态监视器=%d, 游戏时间=%.1f秒", 
            enemyCount, monitorCount, self.gameTime))
    end
end

-- 更新敌人状态监视器
function Game:updateEnemyStatusMonitors(dt)
    local monitorsToRemove = {}
    
    for enemyId, statusData in pairs(self.enemyStatusMonitors) do
        local enemy = statusData.enemyRef
        local monitor = statusData.monitor
        
        if enemy and enemy.data and monitor then
            -- 检查敌人是否还存在
            if not enemy.data.isAlive then
                -- 敌人已死亡，标记为需要清理
                table.insert(monitorsToRemove, enemyId)
            else
                -- 更新位置
                local pos = enemy.data.position
                if pos then
                    monitor:update(dt, pos.x, pos.y)
                end
                
                -- 检查敌人是否死亡
                if enemy.data.health <= 0 then
                    enemy.data.isAlive = false
                    table.insert(monitorsToRemove, enemyId)
                    
                    if self.debugMode then
                        print(string.format("敌人 %s 死亡，清理状态监视器", enemyId))
                    end
                end
            end
        else
            -- 敌人数据无效，标记为需要清理
            table.insert(monitorsToRemove, enemyId)
        end
    end
    
    -- 清理标记的监视器
    for _, enemyId in ipairs(monitorsToRemove) do
        local statusData = self.enemyStatusMonitors[enemyId]
        if statusData and statusData.monitor then
            statusData.monitor:cleanup()
        end
        self.enemyStatusMonitors[enemyId] = nil
        
        if self.debugMode then
            print(string.format("清理敌人状态监视器: %s", enemyId))
        end
    end
end

-- 检测战斗碰撞
function Game:checkCombatCollisions()
    if not self.combatCoreSystem or not self.enemySpawner then return end
    
    local enemies = self.enemySpawner:getEnemies()
    
    -- 检测玩家攻击敌人
    if self.playerEntity and self.spineNode then
        for enemyId, enemy in pairs(enemies) do
            if enemy and enemy.data and enemy.data.isAlive and enemy.spineNode then
                local collisionDetected, damage = self.combatCoreSystem:checkCollision(
                    "player", 
                    enemyId, 
                    self.spineNode, 
                    enemy.spineNode
                )
                
                if collisionDetected and damage > 0 then
                    -- 应用伤害
                    local isDead = self.enemySpawner:applyDamageToEnemy(enemyId, damage)
                    
                    -- 更新状态监视器
                    local statusData = self.enemyStatusMonitors[enemyId]
                    if statusData and statusData.monitor then
                        statusData.monitor:applyDamage(damage)
                    end
                    
                    if self.debugMode then
                        print(string.format("玩家击中敌人 %s, 伤害: %d, 敌人死亡: %s", 
                            enemyId, damage, tostring(isDead)))
                    end
                    
                    if isDead then
                        -- 敌人死亡，会在下一个update循环中清理状态监视器
                        if statusData and statusData.monitor then
                            statusData.monitor:cleanup()
                        end
                        self.enemyStatusMonitors[enemyId] = nil
                    end
                end
            end
        end
    end
    
    -- 检测敌人攻击玩家（需要敌人有攻击动画和命中框）
    -- 这里可以后续添加敌人攻击逻辑
end

-- 更新主菜单状态
function Game:updateMainMenuState(dt)
    -- 主菜单状态下的更新逻辑
    -- 主要处理输入和UI更新
end

-- 更新暂停状态
function Game:updatePausedState(dt)
    -- 暂停状态下的更新逻辑
    -- 只处理输入，不更新游戏逻辑
end

-- 检查测试场景边界
function Game:checkTestSceneBoundaries()
    if not self.playerEntity or not self.testScene then return end
    
    local pos = self.playerEntity.position
    local bounds = self.testScene.sceneBounds
    
    -- X轴边界
    if pos.x < bounds.left then
        pos.x = bounds.left
        self.playerEntity.velocity.x = 0
    elseif pos.x > bounds.right then
        pos.x = bounds.right
        self.playerEntity.velocity.x = 0
    end
    
    -- Y轴边界（防止掉出场景）
    if pos.y < -100 then
        -- 重置玩家位置
        pos.x = 100
        pos.y = 300
        self.playerEntity.velocity.x = 0
        self.playerEntity.velocity.y = 0
        print("玩家掉出场景，已重置位置")
    end
end

-- 处理玩家死亡
function Game:handlePlayerDeath()
    -- 可以在这里添加死亡处理逻辑
    -- 暂时只是重新开始游戏
    print("玩家死亡，重新开始游戏")
    self:restartGame()
end

-- 重新开始游戏
function Game:restartGame()
    -- 清理当前游戏系统
    self:cleanupGameSystems()
    
    -- 重新创建游戏场景（从户外场景开始）
    self:startGame()
end

-- 清理所有资源
function Game:cleanup()
    -- 清理音乐管理器
    if self.musicManager then
        self.musicManager:stopBGM()
        self.musicManager = nil
    end

    -- 清理主菜单
    if self.mainMenu then
        self.mainMenu:cleanup()
        self.mainMenu = nil
    end
    
    -- 清理场景管理器
    if self.sceneManager then
        self.sceneManager:cleanup()
        self.sceneManager = nil
    end
    
    -- 清理游戏资源
    self:cleanupGameSystems()
    
    -- 清理输入系统
    if self.keyboardInput then
        -- 注意：keyboard_input模块可能没有clearAllCallbacks方法
        -- 所以我们只简单地将引用置为nil
        self.keyboardInput = nil
    end
    
    if self.inputManager then
        self.inputManager = nil
    end
    
    -- 清理敌人状态监视器
    for enemyId, statusData in pairs(self.enemyStatusMonitors) do
        if statusData and statusData.monitor then
            statusData.monitor:cleanup()
        end
    end
    self.enemyStatusMonitors = {}
    
    print("游戏资源已完全清理")
end

-- 主游戏循环
local function main()
    -- 创建游戏实例
    local game = Game.new()
    
    -- 初始化游戏
    local initSuccess = game:initialize()
    if not initSuccess then
        return Node()
    end
    
    -- 创建主场景节点用于游戏循环
    local mainScene = Node()
    
    -- 将当前场景添加到主场景
    local currentScene = game.sceneManager:getCurrentScene()
    if currentScene and not currentScene.parent then
        mainScene:addChild(currentScene)
    end
    
    -- 注册游戏更新循环
    mainScene:schedule(function(dt)
        game:update(dt)
    end)
    
    -- 注册退出清理
    mainScene:slot("Cleanup", function()
        game:cleanup()
    end)
    
    return mainScene
end

-- 启动游戏
return main